package org.jvm.instruction.control;

import org.jvm.instruction.base.*;
import org.jvm.rtda.thread.Frame;

/**
 * @author 海燕
 * @date 2023/1/29
 */
public class TABLE_SWITCH implements Instruction {

    private int defaultOffset;
    private int low;
    private int high;
    private int[] jumpOffsets;


    @Override
    public void fetchOperands(ByteCodeReader reader) {
        reader.skipPadding();
        this.defaultOffset = reader.readUint32();
        this.low = reader.readUint32();
        this.high = reader.readUint32();
        int jumpOffsetsCount = this.high - this.low + 1;
        this.jumpOffsets = reader.readUint32s(jumpOffsetsCount);
    }

    @Override
    public void execute(Frame frame) {
        int index = frame.getOperandStack().popInt();
        int offset;
        if (index >= this.low && index <= this.high) {
            offset = this.jumpOffsets[index - this.low];
        } else {
            offset = this.defaultOffset;
        }
        InstructionUtil.branch(frame, offset);
    }
}
